package com.yx.gsyd.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ExcelImport {

    public static short weight = 256 * 19 + 184;
    public static short height = 800;
    public static short imgStartColIndex = 0;

    public static void export(HttpServletResponse response, List<?> list, String fileName, String[] title, String[] columns) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Object[][] values = new Object[list.size()][];

        for (int i = 0; i < list.size(); i++) {
            values[i] = new Object[title.length];
            for (int j = 0; j < columns.length; j++) {
                Object t = list.get(i);
                Class cls = t.getClass();
                String column = columns[j];
                if (column.length() == 0) {
                    throw new Exception("字段不能为空");
                }
                String getMethod = "get" + column.substring(0, 1).toUpperCase() + column.substring(1, column.length());
                Method method = cls.getMethod(getMethod);
                Object obj = method.invoke(t);
                if (obj instanceof Date) {
                    Date date = (Date) obj;
                    values[i][j] = format.format(date);
                } else
                    values[i][j] = obj;

            }
        }
        HSSFWorkbook wb = getHSSFWorkbook(fileName, title, values, null);

        OutputStream os = null;
        // 将文件存到指定位置
        try {
            setResponseHeader(response, fileName);
            os = response.getOutputStream();
            // os = new FileOutputStream("D:/测试Excel.xls");
            //写入excel文件
            wb.write(os);
            os.flush();
        } catch (Exception e) {
            throw new IOException("写入文件出错");
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                throw new IOException("关闭流文件出错");
            }
        }
    }

    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {

            String headStr = "attachment; filename=\"" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + "\"";
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, Object[][] values, HSSFWorkbook wb) {
        // 第一步，创建一个webbook，对应一个Excel文件
        if (wb == null) {
            wb = new HSSFWorkbook();
        }
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow(0);

        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setWrapText(true);
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式

        HSSFCell cell = null;
        //创建标题
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        FileOutputStream fileOut = null;
        BufferedImage bufferImg = null;
        //   HSSFSheet sheet1 = wb.createSheet("test picture");
        //画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
        //创建内容
        for (int i = 0; i < values.length; i++) {
            row = sheet.createRow(i + 1);
            row.setHeight(height);

           /* if (i == values.length - 1) {
                sheet.setColumnWidth(i + 1, 256 * 20 + 184);
          }*/
            for (int j = 0; j < values[i].length; j++) {
                sheet.setColumnWidth(j, weight);
                cell = row.createCell(j);
                if (j == 5) {
                    sheet.setColumnWidth(j, weight * 2);
                }
                if (values[i][j] instanceof String && values[i][j].toString().indexOf("http") != -1) {
                    if (imgStartColIndex == 0)
                        imgStartColIndex = (short) j;
                    //先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
                    try {
                        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                        URL url = new URL(values[i][j].toString());
                        bufferImg = ImageIO.read(url);
                        ImageIO.write(bufferImg, "png", byteArrayOut);

                        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                        //anchor主要用于设置图片的属性
                        HSSFClientAnchor anchor = new HSSFClientAnchor((i + 1), (i + 1), (i + 1), (i + 1), imgStartColIndex, (i + 1), (short) (imgStartColIndex + 1), (i + 2));
//                        anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);
                        anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
                        //插入图片
                        patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
                    } catch (Exception e) {
                        //   e.printStackTrace();
                    }
                } else {
                    if (values[i][j] instanceof String) {
                        cell.setCellStyle(style);
                        cell.setCellValue(values[i][j].toString());
                    } else if (values[i][j] instanceof BigDecimal) {
                        cell.setCellStyle(style);
                        cell.setCellValue(new BigDecimal(values[i][j].toString()).doubleValue());
                    } else if (values[i][j] instanceof Integer) {
                        cell.setCellStyle(style);
                        cell.setCellValue(new BigDecimal(values[i][j].toString()).doubleValue());
                    } else {
                        cell.setCellStyle(style);
                        cell.setCellValue((values[i][j] == null ? "" : values[i][j].toString()));
                    }
                }
            }
        }

        return wb;
    }


}
